package org.shiki.hrm.detail;

import org.shiki.hrm.domain.LoginUser;
import org.shiki.hrm.domain.Permission;
import org.shiki.hrm.mapper.LoginUserMapper;
import org.shiki.hrm.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDatailService implements UserDetailsService  {

	@Autowired
	private LoginUserMapper loginUserMapper;

	@Autowired
	private PermissionMapper permissionMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		LoginUser loginUser = new LoginUser();
		loginUser.setUsername(username);
		LoginUser one = loginUserMapper.selectOne(loginUser);
		Assert.notNull(one, "用户不存在!");
		List<Permission> permissions = loginUserMapper.selectPermissionById(one.getId());
		List<SimpleGrantedAuthority> authorizes = new ArrayList<>();
		permissions.stream().forEach(permission -> {
			SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getSn());
			authorizes.add(authority);
		});
		return new User(one.getUsername(), one.getPassword(), authorizes);
	}
}
